<?php
/**
 * Copyright (c) 2006, PORTALIER Julien
 * 
 * Licensed under The LGPL License
 * Redistributions of files must retain the above copyright notice.
 * 
 * @copyright    Copyright (c) 2006, Julien PORTALIER
 * @link         http://code.google.com/p/feather-cm
 * @license      http://www.opensource.org/licenses/lgpl-license.php The LGPL License
 */

class HtmlPage extends ActiveRecord
{
	// read
	
	function & getList()
	{
		$this->process = Q_PROCESS_LITE;
		$this->order('id DESC');
		return $this->findAll('id,title');
	}
	
	// create & update
	
	function & getDefault($id=null)
	{
		$data = array('HtmlPage' => array('id' => empty($id) ? $this->id : $id));
		return $data;
	}
	
	function beforeValidate()
	{
		$this->data['HtmlPage']['id'] = $this->id;
		
		if (empty($this->validate))
		{
			$this->validate = array(
				'id' => array(
					Valid::NotEmpty  => _("An identifier is required."),
					'validateUnique' => _("This identifier is already in use.")),
				'body'  => array(Valid::NotEmpty => _("The page can't be empty."))
			);
		}
	}
	
	function beforeSave()
	{
		# generates HTML from syntax
		if (isset($this->data['HtmlPage']['body']))
		{
			Load::libs('markdown_syntax');
			$MarkdownSyntax = new MarkdownSyntax;
			
			$this->data['HtmlPage']['body_html'] = $MarkdownSyntax->transform($this->data['HtmlPage']['body'], MarkdownSyntax::AllowMarkup);
			$this->data['HtmlPage']['body_toc']  = $MarkdownSyntax->generateTableOfContent();
		}
		
		# preview? don't save!
		return !isset($this->params['form']['preview']);
	}
	
	function rename($new_id)
	{
		$this->condition('id', $new_id);
		$check = $this->find('id');
		
		if (empty($check))
			return $this->saveField('id', $new_id);
		
		return sprintf(_('Error: the page /%s already exists.'), $new_id);
	}
}
?>